package com.cwl.mc.controller;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cwl.common.dto.UEResult;
import com.cwl.common.dto.UERetCode;
import com.cwl.mc.handler.IMcHandler;
import com.cwl.utils.SpringContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 功能描述：
 *     Api入口
 * @author cwledit
 * @date 2019/6/20
 */
@Slf4j
@Controller
@CrossOrigin
public class McApiController extends BaseController {


    /**
     * API 入口类
     * @return
     */
    @RequestMapping(value = "/mc/api/{trcode}")
    @ResponseBody
    public UEResult api(@PathVariable String trcode, @RequestBody(required = false) String content, @RequestParam Map<String,Object> paramRequest) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        if (StringUtils.isBlank(trcode)) {
            return UEResult.error(UERetCode.RET_0102);
        }
        if (paramRequest == null && StringUtils.isNotEmpty(content)) {
            return UEResult.error(UERetCode.RET_0103);
        }
        JSONObject param;
        if (paramRequest == null || paramRequest.isEmpty()) {
            if (StringUtils.isNotEmpty(content)) {
                param = JSON.parseObject(content);
            } else {
                return UEResult.error(UERetCode.RET_0103);
            }
        } else {
            param = new JSONObject(paramRequest);
        }
        if (param == null) {
            return UEResult.error(UERetCode.RET_0104);
        }
        IMcHandler handler = SpringContextHolder.getBean(trcode);
        if (handler == null) {
            return UEResult.error(UERetCode.RET_0105);
        } else {
            UEResult result;
            try {
                result = handler.handler(param);
                stopWatch.stop();

                log.info(trcode + " execute time is :" + stopWatch.getTime(TimeUnit.MILLISECONDS) + " ms" + " response :" + result.toString());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return UEResult.error(ExceptionUtil.getMessage(e));
            }
            return result;
        }
    }





}
